package cn.lzb.book.server.service.impl;

import cn.lzb.book.server.common.exception.BaseExceptionEnums;
import cn.lzb.book.server.common.exception.BookServerException;
import cn.lzb.book.server.component.convert.BookConvert;
import cn.lzb.book.server.dao.po.BookPo;
import cn.lzb.book.server.dao.repository.BookRepository;
import cn.lzb.book.server.entity.dto.BookInfo;
import cn.lzb.book.server.entity.dto.BookPageQuery;
import cn.lzb.book.server.entity.dto.Ids;
import cn.lzb.book.server.entity.dto.SystemUser;
import cn.lzb.book.server.entity.vo.BookDetailVo;
import cn.lzb.book.server.entity.vo.BookPageVo;
import cn.lzb.book.server.service.IBookService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author liuzhibo
 * @date 2024/8/28 16:21
 **/
@RequiredArgsConstructor
@Service
public class BookServiceImpl implements IBookService {

    private final BookRepository bookRepository;

    @Override
    public BookDetailVo queryDetails(Long id) {
        BookPo bookPo = bookRepository.getById(id);
        return BookConvert.INSTANCE.bookPo2DetailVo(bookPo);
    }

    @Override
    public void save(BookInfo bookInfo, SystemUser systemUser) {
        BookPo bookPo = BookConvert.INSTANCE.bookInfo2Po(bookInfo);
        bookPo.setOperator(systemUser.getName());
        bookPo.setGmtModified(new Date());
        bookPo.setGmtCreated(new Date());
        bookRepository.saveOrUpdate(bookPo);
    }

    @Override
    public void update(BookInfo bookInfo, SystemUser systemUser) {
        if (Objects.isNull(bookInfo.getId())) {
            throw new BookServerException(BaseExceptionEnums.Common.PARAMS_MISS);
        }
        BookPo bookPo = BookConvert.INSTANCE.bookInfo2Po(bookInfo);
        bookPo.setOperator(systemUser.getName());
        bookPo.setGmtModified(bookPo.getGmtCreated());
        bookRepository.updateById(bookPo);
    }

    @Override
    public void deleteByIds(Ids ids, SystemUser systemUser) {
        bookRepository.deleteByIds(ids.getIds());
    }

    @Override
    public IPage<BookPageVo> queryPage(BookPageQuery bookPageQuery) {
        Page<BookPo> bookPoPage = bookRepository.queryPage(bookPageQuery);
        return bookPoPage.convert(BookConvert.INSTANCE::bookPo2PageVo);
    }
}
